package com.apimanage.auth.service.impl;


import com.apimanage.common.dto.UserDTO;
import com.apimanage.common.service.UserCenterService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户详情服务实现
 * 实现Spring Security的UserDetailsService接口
 * 用于加载用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    // 设置check=false，避免因为user-center服务不可用而导致auth-center启动失败
    @DubboReference(check = false, timeout = 3000)
    private UserCenterService userCenterService;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("开始加载用户信息: username = {}", username);
        
        try {
            // 通过UserCenterService获取用户信息，利用服务治理框架管理连接
            UserDTO user = userCenterService.getUserByUsername(username);
            
            logger.info("从UserCenterService获取用户信息: user = {}", user != null ? "存在" : "不存在");
            
            // 如果用户不存在，抛出异常
            if (user == null) {
                logger.warn("用户不存在: {}", username);
                throw new UsernameNotFoundException("用户不存在: " + username);
            }
            
            logger.info("用户信息: username = {}, status = {}, passwordExists = {}, role = {}", 
                       user.getUsername(), user.getStatus(), user.getPassword() != null && !user.getPassword().isEmpty(), user.getRole());
            
            // 检查用户状态
            if (user.getStatus() == null || user.getStatus() == 0) {
                logger.warn("用户已禁用: {}, status = {}", username, user.getStatus());
                throw new UsernameNotFoundException("用户已禁用: " + username);
            }
            
            // 设置用户角色和权限
            Set<SimpleGrantedAuthority> authorities = new HashSet<>();
            
            // 根据数据库中的role字段设置角色和权限
            String role = user.getRole();
            if ("admin".equals(role)) {
                // 管理员角色
                logger.info("用户 {} 是管理员角色，添加管理员权限", username);
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                authorities.add(new SimpleGrantedAuthority("admin:view"));
                authorities.add(new SimpleGrantedAuthority("admin:edit"));
            } else {
                // 普通用户角色
                logger.info("用户 {} 是普通用户角色，添加用户权限", username);
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                authorities.add(new SimpleGrantedAuthority("user:view"));
                authorities.add(new SimpleGrantedAuthority("user:edit"));
            }
            
            logger.info("用户 {} 的权限列表: {}", username, authorities);
            
            // 创建UserDetails对象并返回
            UserDetails userDetails = new User(
                    user.getUsername(),
                    user.getPassword(),  // 使用用户在数据库中的实际密码
                    true,  // 账户是否启用
                    true,  // 账户是否过期
                    true,  // 凭据是否过期
                    true,  // 账户是否锁定
                    authorities  // 用户权限
            );
            
            logger.info("用户 {} 的UserDetails对象创建完成，准备返回", username);
            return userDetails;
        } catch (UsernameNotFoundException e) {
            // 重新抛出用户名不存在异常
            throw e;
        } catch (Exception e) {
            logger.error("加载用户信息异常: {}", e.getMessage());
            throw new UsernameNotFoundException("加载用户信息失败: " + e.getMessage(), e);
        }
    }
}